package com.platform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.platform.annotation.SysLog;
import com.platform.common.Const;
import com.platform.common.ServerResponse;
import com.platform.service.IJedisClientService;
import com.platform.service.ISolrSearchService;
import com.platform.util.ListSub;
import com.platform.util.NumberUtil;
import com.platform.util.SearchConsumablesUtil;
import com.platform.util.StringUtil;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * solr查询筛选排序
 */
@Service("iSolrSearchService")
public class SolrSearchServiceImpl implements ISolrSearchService {

    @Autowired
    private IJedisClientService iJedisClientService;

    /**
     * 耗材价格查询字段查询结果筛选排序
     * @param paramMap
     * @param request
     * @return
     */
    @SysLog("solr大字段排序")
    public ServerResponse<PageInfo> sort(Map paramMap, HttpServletRequest request) throws IOException {
        String sessionId = request.getSession().getId();
        int pageNum = NumberUtil.safeToNumber(paramMap.get("pageNum"));
        int pageSize = NumberUtil.safeToNumber(paramMap.get("pageSize"));
        //获取redis缓存
        String redisStr = iJedisClientService.get(sessionId);
        if(StringUtil.isNotEmpty(redisStr) && pageNum > 1){//翻页情况下有缓存直接返回
            List<Map> cacheList =(List<Map>) JSONObject.parse(redisStr);
            ListSub<Map> listSub = new ListSub<Map>(pageNum, pageSize, cacheList);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(listSub.getTotal());
            pageInfo.setPages(listSub.getPages());
            pageInfo.setPageSize(listSub.getPageSize());
            pageInfo.setList(listSub.getList());
            return ServerResponse.createBySuccess(pageInfo);
        }
        SolrDocumentList list = SearchConsumablesUtil.selectByParamMap(paramMap);
        if(list == null){
            return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
        }
        String productName = StringUtil.valueOfString(paramMap.get("productname"));//产品名称
        String sm = StringUtil.valueOfString(paramMap.get("sm"));//型号规格
        String mb = StringUtil.valueOfString(paramMap.get("mb"));//厂家
        if(StringUtil.isNotEmpty(productName)){//产名名称字段排序
            if(productName.length() >= 5){//条件长度大于五则进行分词
                int matchNum;//匹配次数
                for (int i=0;i<list.size();i++){
                    matchNum = 0;
                    String productName2 = StringUtil.valueOfString(list.get(i).get("productname"));//产品名称
                    //排序前筛选掉无用数据
                    StringReader sr=new StringReader(productName);//分词搜索条件
                    Lexeme lex;
                    IKSegmenter ik=new IKSegmenter(sr, false);
                    while((lex=ik.next())!=null){
                        String pstr = lex.getLexemeText();
                        //匹配上就加1
                        if(productName2.contains(pstr)){
                            matchNum++;
                        }
                    }
                    if(matchNum < 2){//少于二次匹配的删除
                        list.remove(i);
                        i--;
                    }
                }
            }
            Collections.sort(list, new Comparator<SolrDocument>() {
                @Override
                public int compare(SolrDocument o1, SolrDocument o2) {
                    String productname = StringUtil.valueOfString(o1.get("productname"));
                    String pruductName2 = StringUtil.valueOfString(o2.get("productname"));
                    if( productName.equals(productname) || productName.equals(pruductName2)){
                        return -1;
                    }
                    if(productName.contains(productname) || productname.contains(productName)||
                            productName.contains(pruductName2) || pruductName2.contains(productName)){
                        return 0;
                    }

                    return 1;
                }
            });
            //价格排序
            Collections.sort(list, new Comparator<SolrDocument>() {
                @Override
                public int compare(SolrDocument o1, SolrDocument o2) {
                    double price = NumberUtil.safeToDouble(o1.get("price"));
                    double price2 = NumberUtil.safeToDouble(o2.get("price"));
                    if(price < price2){
                        return -1;
                    }
                    if(price <= price2){
                        return 0;
                    }
                    return 1;
                }
            });
        }

        if(StringUtil.isNotEmpty(sm)){//型号规格筛选
            if(sm.length() >= 5){//条件长度大于五则进行分词
                int matchNum;//匹配次数
                for (int i=0;i<list.size();i++){
                    matchNum = 0;
                    String model = StringUtil.valueOfString(list.get(i).get("model"));//型号
                    String specifications = StringUtil.valueOfString(list.get(i).get("specifications"));//规格
                    //排序前筛选掉无用数据
                    StringReader sr=new StringReader(sm);//分词搜索条件
                    Lexeme lex;
                    IKSegmenter ik=new IKSegmenter(sr, false);
                    while((lex=ik.next())!=null){
                        String pstr = lex.getLexemeText();
                        //匹配上就加1
                        if(model.toLowerCase().contains(pstr) || specifications.toLowerCase().contains(pstr)){
                            matchNum++;
                        }
                    }
                    if(matchNum < 2){//少于二次匹配的删除
                        list.remove(i);
                        i--;
                    }
                }
            }
            Collections.sort(list, new Comparator<SolrDocument>() {
                @Override
                public int compare(SolrDocument o1, SolrDocument o2) {
                    String model = StringUtil.valueOfString(o1.get("model"));
                    String specifications = StringUtil.valueOfString(o1.get("specifications"));
                    if( sm.equals(model) || sm.equals(specifications)){
                        return -1;
                    }
                    if(model.contains(sm) || specifications.contains(sm)){
                        return 0;
                    }
                    return 1;
                }
            });
            //价格排序
            Collections.sort(list, new Comparator<SolrDocument>() {
                @Override
                public int compare(SolrDocument o1, SolrDocument o2) {
                    String model = StringUtil.valueOfString(o1.get("model"));
                    String specifications = StringUtil.valueOfString(o1.get("specifications"));
                    double price = NumberUtil.safeToDouble(o1.get("price"));
                    double price2 = NumberUtil.safeToDouble(o2.get("price"));
                    if( (sm.equals(model) || sm.equals(specifications)) && price < price2){
                        return -1;
                    }
                    if((model.contains(sm) || specifications.contains(sm))&& price < price2){
                        return 0;
                    }
                    return 1;
                }
            });
        }
        if(StringUtil.isNotEmpty(mb)){//生产厂家
            Collections.sort(list, new Comparator<SolrDocument>() {
                @Override
                public int compare(SolrDocument o1, SolrDocument o2) {
                    String manufacture = StringUtil.valueOfString(o1.get("manufacture"));
                    if( mb.equals(manufacture)){
                        return -1;
                    }
                    if(manufacture.contains(mb)){
                        return 0;
                    }
                    return 1;
                }
            });
            //价格排序
            Collections.sort(list, new Comparator<SolrDocument>() {
                @Override
                public int compare(SolrDocument o1, SolrDocument o2) {
                    String manufacture = StringUtil.valueOfString(o1.get("manufacture"));
                    double price = NumberUtil.safeToDouble(o1.get("price"));
                    double price2 = NumberUtil.safeToDouble(o2.get("price"));
                    if(mb.equals(manufacture)  && price < price2){
                        return -1;
                    }
                    if(mb.contains(manufacture) && price < price2){
                        return 0;
                    }
                    return 1;
                }
            });
        }
        ListSub<SolrDocument> listSub = new ListSub<SolrDocument>(pageNum, pageSize, list);
        iJedisClientService.set(sessionId,JSONObject.toJSONString(list));
        iJedisClientService.expire(sessionId,600);//缓存时间
        PageInfo pageInfo = new PageInfo();
        pageInfo.setTotal(listSub.getTotal());
        pageInfo.setPages(listSub.getPages());
        pageInfo.setPageSize(listSub.getPageSize());
        pageInfo.setList(listSub.getList());
        return ServerResponse.createBySuccess(pageInfo);
    }
}
